<template>
  <div class="home-container">
    <van-nav-bar title="今日头条" fixed />
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <articleItem
          v-for="item in artList"
          :key="item.id"
          :title="item.title"
          :comment="item.comm_count"
          :author="item.aut_name"
          :pubTime="item.pubdate"
          :imgList="item.cover"
          :article="item"
          @remove-article="removeArticle"
        ></articleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import request from '@/utils/request.js'
import articleItem from '@/components/articleItem.vue'

export default {
  name: 'Home',

  data() {
    return {
      show: true,
      page: 1,
      limit: 10,
      artList: [],
      loading: true,
      refreshing: true,
      finished: false
    }
  },
  components: {
    articleItem
  },
  created() {
    this.initArticleList()
  },
  computed: {},
  methods: {
    async initArticleList() {
      // 发起GET请求，获取文章的列表数据
      // 解构赋值
      const { data: res } = await request.get('/articles', {
        //   请求参数
        params: {
          _page: this.page,
          _limit: this.limit
        }
      })
      this.artList = [...this.artList, ...res]
      this.loading = false
      console.log(this.artList)
      if (res.length === 0) {
        this.finished = true
      }
    },
    // 滚动到底部
    onLoad() {
      console.log('loading')
      this.page++
      // if (this.loading === false) {
      this.initArticleList()
      // }
    },
    onRefresh() {
      console.log('refreshing')
      // 清空列表数据
      this.finished = false

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      if (this.refreshing) {
        this.page = 1
        this.artList = []
        this.initArticleList()
        this.refreshing = false
      }
      this.loading = true
    },
    removeArticle(id) {
    // 对原数组进行 filter 方法的过滤
      this.artList = this.artList.filter(item => item.art_id.toString() !== id)
    }
  }
}
</script>
<style lang="less" scoped>
.home-container {
  padding: 46px 0 50px 0;
  /deep/ .van-nav-bar {
    background: #007bff;
  }
  /deep/ .van-nav-bar__title {
    color: white;
  }
}
</style>
